/*
 * To run:
 * set the login settings in connectionSettings.settings
 * set DataPath in connectionSettings.settings to point to the folder that holds TextSL.mdf
 * 
 * To use:
 * set: send an im to the server user of the form "UNRDB set <name> <value>"
 * get: send an im of the form "UNRDB get <name>" => will return "UNRDB value <name> <value>"
 */

using System;
using System.Collections.Generic;
using System.Text;
using libsecondlife;
using System.Data.Sql;
using System.Data.SqlClient;

namespace dataServer
{
    class Program
    {
        static SqlConnection connection;
        static SecondLife client;
        static Dictionary<string, string> values;
        static connectionSettings settings = new connectionSettings();

        static void Main(string[] args)
        {
            Console.WriteLine("connecting to database...");
            string dbname = settings.DataPath + "TextSL.mdf";
            string constr = string.Format("Data Source=(local)\\SQLEXPRESS;AttachDbFilename=\"{0}\";Integrated Security=True;Connect Timeout=30;User Instance=True", dbname); 
            connection = new SqlConnection(constr);
            connection.Open();
            Console.WriteLine("connected");

            values = new Dictionary<string, string>();

            Console.WriteLine("connecting...");
            client = new SecondLife();

            client.Network.OnDisconnected += new NetworkManager.DisconnectedCallback(Network_OnDisconnected);

            client.Self.OnInstantMessage += new AgentManager.InstantMessageCallback(Self_OnInstantMessage);

            login();
        }

        static void Network_OnDisconnected(NetworkManager.DisconnectType reason, string message)
        {
            Console.WriteLine("reconnecting...");
            login();
        }

        static void Self_OnInstantMessage(InstantMessage im, Simulator simulator)
        {
            if (im.Message.StartsWith("UNRDB"))
            {
                string[] toks = im.Message.Split();

                if (toks.Length >= 4 && toks[1] == "set")
                {
                    string name = toks[2], val = toks[3];
                    Console.WriteLine("set " + name + " " + val);

                    SqlCommand cmd = new SqlCommand("select ObjectName from ObjectId where ObjectID = '" + name + "'",
                        connection);
                    SqlDataReader reader = cmd.ExecuteReader();
                    if (reader.Read())
                    {
                        reader.Close();
                        SqlCommand update = new SqlCommand("update ObjectId set objectName = '" + val +
                            "' where ObjectID = '" + name + "'", connection);
                        update.ExecuteNonQuery();
                    }
                    else
                    {
                        reader.Close();
                        SqlCommand insert = new SqlCommand("insert into ObjectId (ObjectID, ObjectName) values ('" +
                            name + "', '" + val + "')", connection);
                        insert.ExecuteNonQuery();
                    }
                }
                else if (toks.Length >= 3 && toks[1] == "get")
                {
                    string name = toks[2];
                    string val = "None";

                    SqlCommand select = new SqlCommand("select ObjectName from ObjectId where ObjectID = '" +
                        name + "'", connection);
                    SqlDataReader reader = select.ExecuteReader();
                    if (reader.Read())
                        val = reader.GetString(0);
                    reader.Close();

                    Console.WriteLine("get " + name + " " + val);
                    client.Self.InstantMessage(im.FromAgentID, "UNRDB value " + toks[2] + " " + val);
                }
            }
        }

        static void login()
        {
            if (!client.Network.Connected)
                client.Network.Login(settings.FirstName, settings.LastName, settings.Password, "UNRDataServer", "0.1");
        }
    }
}
